package com.common.web.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.common.api.exception.CommonException;
import com.common.util.EnvironmentUtil;
import com.common.web.dto.response.RestResponse;

/**
 * 请求拦截器
 *  登录拦截器
 * @author ficus
 */
@Component
public class JwtTokenAuthHandlerInterceptor extends HandlerInterceptorAdapter {
	
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	if(EnvironmentUtil.isDevEnvi()) {
    		// 开发环境无需验证
    		return true;
    	}
    	if("OPTIONS".equals(request.getMethod())) {
    		return true;
    	}
    	// 拿到请求头
        try {
          jwtTokenUtil.validateToken(request);
		} catch (CommonException e) {
			response.setCharacterEncoding("UTF-8");//设置编码格式
            response.setContentType("application/json;charset=UTF-8");
//            String originalURL = request.getHeader("Origin");
//            if (originalURL != null) {
//                response.addHeader("Access-Control-Allow-Origin", originalURL);
//            }
            response.addHeader("Access-Control-Allow-Credentials", "true");
            RestResponse restResponse=RestResponse.failure(e.getErrorDetail());
            restResponse.setResultCode(e.getErrorCode()); //需要跳转登录界面
            restResponse.setResultMsg(e.getErrorMsg());
			String msg=JSON.toJSONString(restResponse);
			response.getOutputStream().write(msg.getBytes("UTF-8"));
			response.getOutputStream().flush();
			return false;
		}
        return  true;
    }
}
